

/////////////////////////

axios.interceptors.request.use(config=> {
    return config;
}, err=> {
   // alert(JSON.stringify(err));
    return Promise.resolve(err);
})
axios.interceptors.response.use(data=> {

    return data;
}, err=> {
   // alert(JSON.stringify(err));
    return Promise.resolve(err);
})
////////////////////////////////////////


const translateApi=(api)=>{
    let url=M.config.baseUrl(api) ;
    if(!api.startsWith("http")){
        api=url
    }
    return api;
}


const post  = async (api, params = {},headers) => {
    api=translateApi(api)
    headers=  Object.assign(headers||{},{"token":sessionStorage.getItem('token')})
    const result = await axios( {
        url:api,
        method: 'post',
        params: {},
        headers:headers,
        data: params,
        getResponse: true,
        responseType: 'json',
    });
    return result.data;
}


const get = async (api, params = {},headers) => {
    api=translateApi(api)
    headers=  Object.assign(headers||{},{"token":sessionStorage.getItem('token')})
    const result = await axios( {
        url:api,
        method: 'get',
        params: params,
        headers:headers,
        data: {},
        getResponse: true,
        responseType: 'json',

    });
    return result.data;
};

const pureGet = async (api, params = {},headers) => {
    const result = await axios( {
        url:api,
        method: 'get',
        params: params,
        headers:headers||{},
        data: {},
        getResponse: true,
        responseType: 'json',

    });
    return result.data;
};

//远程mock
const get0=async (url,params,headers)=>{
   return  pureGet(M.config.baseMockUrl(url),params,headers)
}
//本地mock
const get1=async (url,params,headers)=>{
    return  pureGet(M.config.baseLocalMockUrl(url),params,headers)
}

const layUiSuccessHandlel=async (data)=>{
    if(data.code !=0){
        layui.layer.msg(data.msg)
    }else {
        layui.layer.msg("success")
    }
}
//页面传参用
window.M.setPageParams=(state) => {
    sessionStorage.setItem('pageParams',JSON.stringify(state));
}

window.M.getPageParams = () => {
    return JSON.parse(sessionStorage.getItem('pageParams'));
}

window.M.removePageParams = () => {
    sessionStorage.removeItem('pageParams');
}


window.M.response={}
window.M.response.layUiSuccessHandlel=layUiSuccessHandlel;


//将ajax请求挂到全局对象M上
window.M.request={}
window.M.request.get=get;
window.M.request.get0=get0;
window.M.request.get1=get1;
window.M.request.post=post;
window.M.request.reqByReq = async (url,req) => {
    if(req.method==="get"){
        let result=  await get(url,req.params,req.headers)
        return result;
    }
    if(req.method==="post"){
        let result= await post(url,req.params,req.headers)
        return result;
    }
};